#include "servertcp.h"
ServerTcp* ServerTcp::global_server =nullptr;
ServerTcp::ServerTcp()
{

}
void ServerTcp::incomingConnection(qintptr handle)
{
    TcpSocket *tempsock = new TcpSocket(handle);
    Client_Server *tempserver = new Client_Server(tempsock);
    qDebug()<<"ADD"<<tempsock->Sock.peerAddress();
    qDebug()<<"ADD"<<tempsock->Sock.peerPort();
    Server_Main::Online_Usr.push_back(tempserver);
    

    connect(this,SIGNAL(sig_write(TcpSocket*,QByteArray)),this,SLOT(slot_writedata(TcpSocket*,QByteArray)));

    connect(tempsock,SIGNAL(sig_sockdisconnect(TcpSocket*)),this,SLOT(slot_sockdisconnected(TcpSocket*)));

}
void ServerTcp::Start()
{
    if(listen(QHostAddress::Any, 6677))
    {
        qDebug() << "isListening";
    }
    else
    {
        qDebug() << "notListening";
    }
}
void ServerTcp::Stop()
{
    close();
}
void ServerTcp::slot_sockdisconnected(TcpSocket *Sock)
{
    emit sig_sockdisconnect(Sock);
    qDebug()<<"Exit"<<Sock->Sock.peerAddress();
    qDebug()<<"Exit"<<Sock->Sock.peerPort();

    Client_Server a(Sock);

    Server_Main::Online_Usr.removeAll(&a);
}
void ServerTcp::slot_sockdata(TcpSocket *Sock)
{
    emit sig_getdata(Sock);
}
void ServerTcp::slot_writedata(TcpSocket *Sock , QByteArray data)
{
    if(Sock->EnableTrans== 1)
    {
        qDebug()<<"size"<<data.size();
        qDebug()<<Sock->Sock.write(data);
        Sock->EnableTrans = 0;
    }


}
